##########################################################################################

library(data.table)
library(optparse)
library(parallel)
library(dplyr)
library(RColorBrewer)
library(ggplot2)
library(ggrepel)

##########################################################################################

option_list <- list(
    make_option(c("--sample_list_file"), type = "character"),
    make_option(c("--input_file"), type = "character"),
    make_option(c("--gtf_file"), type = "character"),
    make_option(c("--q_t"), type = "character"),
    make_option(c("--foldchange_t"), type = "character"),
    make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
    sample_list_file <- "~/20220915_gastric_multiple/rna_combine/analysis/config/tumor_normal.list"
    input_file <- "~/20220915_gastric_multiple/rna_combine/analysis/images/DiffGene/DiffGene.tsv"
    out_path <- "~/20220915_gastric_multiple/rna_combine/analysis/images/DiffGene"
    q_t <- 0.05
    foldchange_t <- 1.5
    gtf_file <- "~/ref/GTF/gencode.v19.ensg_genename.txt"

}

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

sample_list_file <- opt$sample_list_file
input_file <- opt$input_file
out_path <- opt$out_path
gtf_file <- opt$gtf_file
q_t <- as.numeric(opt$q_t)
foldchange_t <- as.numeric(opt$foldchange_t)

dir.create(out_path , recursive = T)

##########################################################################################

info <- data.frame(fread(sample_list_file))
dat_diff <- data.frame(fread(input_file))
dat_gtf <- data.frame(fread(gtf_file , header = F))
colnames(dat_gtf) <- c("gene_id" , "Hugo_Symbol")
dat_diff <- merge( dat_diff , dat_gtf , by = "gene_id" )

##########################################################################################

class_type <- c( "Normal" , "IM" , "IGC" , "DGC")

image_name <- paste0( out_path , "/DiffGene.HugoSymbol.tsv" )
write.table( dat_diff , image_name , row.names = F , quote = F , sep = "\t" )

##########################################################################################

#过滤差异基因；
df3 <- dat_diff
df3$PValue <- df3$padj
df3$log2FC <- df3$log2FoldChange
df3$gene_id <- df3$Hugo_Symbol
df3$Groups <- paste0( df3$class1 , " vs " , df3$class2  )

tb <- as_tibble(df3)
df4 <- filter(tb,abs(log2FC)>=foldchange_t , PValue<q_t)

#添加上下调标签；
df4$Label <- case_when(df4$log2FC > 0 ~ "Up", df4$log2FC < 0 ~ "Down")
df4$Qlabel <- case_when(df4$PValue <= 0.05 ~ "Red", df4$PValue > 0.05 ~ "Black")

#筛选每个分组中差异倍数TOP2的基因（上下调各1个）；
df5 <- df4 %>% group_by(Groups,Label) %>% top_n(20,abs(log2FC))

#根据所需目的基因，进一步对数据分组；
groups <- unique(df4$Groups)
df_sub <- data.frame()
for (i in groups){
    df4_sub<- filter(df4,Groups == i)
    df5_sub<- filter(df5,Groups == i)
    df4_sub$Top <-case_when(df4_sub$gene_id %in% df5_sub$gene_id ~ "Yes",
    !(df4_sub$gene_id %in% df5_sub$gene_id ) ~ "No")
    df_sub <-rbind(df_sub,df4_sub)
}
#提取非Top2的基因表格；
df6 <- filter(df_sub,df_sub$Top=="No")
#提取Top2的基因表格；
df7_up <- filter(df_sub,df_sub$Top=="Yes"& df_sub$Label=="Up")
df7_down <- filter(df_sub,df_sub$Top=="Yes" & df_sub$Label=="Down")

#数据准备；
dt7_up <- as_tibble(df7_up)
up <- dt7_up %>% group_by(Groups) %>% summarise(max(log2FC))
dt7_down <- as_tibble(df7_down)
down <- dt7_down %>% group_by(Groups) %>% summarise(min(log2FC))
#生成数据框；
df_col <- data.frame(up,down[2])
max <- max(max(df_col$max.log2FC.),max(abs(df_col$min.log2FC.)))
expan <- max/20


#绘制背景条；
p <- ggplot()+
geom_col(data = df_col, aes(x = Groups, y = max.log2FC.+expan),width =0.8, fill = "grey90",alpha=0.4,show.legend = F)+
geom_col(data = df_col,aes(x = Groups, y = min.log2FC.-expan),width =0.8, fill = "grey90",alpha=0.4,show.legend = F)

#使用不同组的差异基因绘图；
p1 <- p + geom_jitter(data = df6,
aes(x = Groups, y = log2FC, color = Label),
size = 0.6,width =0.4,show.legend = F)

#继续添加Top2基因对应的点；
p2 <- p1+geom_jitter(data = df7_down,
aes(x = Groups, y = log2FC, color = Label),
size = 1.8,alpha=1,width =0.4,show.legend = T)+
geom_jitter(data = df7_up,
aes(x = Groups, y = log2FC, color = Label),
size = 1.8,alpha=1,width =0.4,show.legend = T)


#自定义半透明颜色（绿红）；
#mycol <- c("#99CC00","#FF99CC")
#mycol <- c("#99CC00","#FF9999")
#mycol <- c("#00a99e","#6bc72b")
mycol <- c("#6bc72b","#ff5a20")
p3 <- p2 + scale_colour_manual(name="",values=alpha(mycol,0.9))

p4 <- p3+geom_text_repel(data=df7_up,aes(x = Groups, y = log2FC,label=gene_id),
force=1,
color="grey20",
size=2.5,
point.padding = 0.1,
arrow = arrow(length = unit(0.01, "npc"), type = "open", ends = "last"),
max.overlaps = 100 ,
segment.color="grey20",
segment.size=0.4,
segment.alpha=0.8)+
geom_text_repel(data=df7_down,aes(x = Groups, y = log2FC,label=gene_id),
force=1,
color="grey20",
size=2.5,
point.padding = 0.1,
arrow = arrow(length = unit(0.01, "npc"), type = "open", ends = "last"),
segment.color="grey20",
segment.size=0.4,
segment.alpha=0.8)

#添加X轴的cluster色块标签：
dfbox<-data.frame(groups,
y=0,
label=c(1:length(groups)))
#使用geom_bar比geom_tile的图例更干净一点；
p5 <- p4+geom_bar(data=dfbox,
aes(x=groups,y=y+0.8,fill=groups),stat = "identity",width = 0.8)+
geom_bar(data=dfbox,
aes(x=groups,y=y-0.8,fill=groups),stat = "identity",width = 0.8)

#自定义颜色；
mycolor <- c("#0077c1","#00a99e","#6bc72b","#ff5a20","#ff1620","#752995")
p6 <- p5+scale_fill_manual(name="Groups",values=alpha(mycolor,1))


#修改X/Y轴标题，添加序号：
p7 <- p6+labs(x="",y="log2FC")+
scale_y_continuous(limits = c(-15, 15),
breaks = c(-15, -10, -5,0,5,10,15),
expand = expansion(add = 0))+
geom_text(data=dfbox,
aes(x=groups,y=y,label=label),
size =5,
color ="white")

#自定义主题；
mytheme <- theme_classic()+theme(axis.line.x = element_blank(),
axis.ticks.x = element_blank(),
axis.text.x = element_blank())
p8 <- p7+mytheme

image_name <- paste0( out_path , "/DiffGene_CombinePlot.pdf" )
ggsave( image_name , p8 )
